import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';
import { HubConnection, HubConnectionBuilder } from '@microsoft/signalr';

@Injectable({
  providedIn: 'root'
})
export class SignalRService {
  private hubConnection: HubConnection;
  private receivedMessageSubject: Subject<String> = new Subject<String>();

  constructor() {
    this.hubConnection = new HubConnectionBuilder()
      .withUrl('https://localhost:44322/msgHub') // 根据你的后端 SignalR Hub 的 URL 进行设置
      .build();
  }

  public startConnection = () => {
    this.hubConnection
      .start()
      .then(() => console.log('SignalR Connection Started')) // 连接成功
      .catch(err => console.log('Error while starting SignalR connection:', err)); // 连接失败

    this.hubConnection.on('ReceiveMessage', (message: String) => {
      this.receivedMessageSubject.next(message);
    });
  };

  public getReceivedMessage(): Subject<String> {
    return this.receivedMessageSubject;
  }
}
